package com.lh1010.s3.config;

import org.beetl.core.Context;
import org.beetl.core.Function;
import org.beetl.core.misc.PrimitiveArrayUtil;
import org.springframework.context.annotation.Configuration;

import java.util.Collection;
import java.util.Map;

/**
 *  beetsql 原来的isEmpty 在判断List时，list大小等于0 会返回false。现方法已优化
 * @author 王帅杰
 */
@Configuration
public class EmptyPlusExpressionFunction implements Function {

    @Override
    public Boolean call(Object[] paras, Context ctx) {
        Object result = paras[0];
        if (result == null) {
            return true;
        }
        if (result instanceof String) {
            return ((String) result).trim().length() == 0;
        } else if (result instanceof Collection) {
            return ((Collection) result).isEmpty();
        } else if (result instanceof Map) {
            return ((Map) result).size() == 0;
        } else if (result.getClass().isArray()) {
            return result.getClass().getComponentType().isPrimitive()
                    ? PrimitiveArrayUtil.getSize(result) == 0
                    : ((Object[]) result).length == 0;
        } else {
            return false;
        }
    }
}
